﻿using JC_DirectBroadcast.Infrastructure.Extensions;
using JC_DirectBroadcast.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Net;
using Microsoft.AspNetCore.Authentication.Cookies;
using Swashbuckle.AspNetCore.Swagger;
using System.Reflection;
using System.IO;
using Autofac;
using JC_DirectBroadcast.Core.Entity;
using JC_DirectBroadcast.Repository.Interface;

namespace JC_DirectBroadcast.Admin
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc(options =>
            {

            })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .ConfigureApiBehaviorOptions(options =>
                {
                    options.SuppressModelStateInvalidFilter = true;
                    options.SuppressInferBindingSourcesForParameters = true;
                });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.Cookie.HttpOnly = true;
                    options.Cookie.Name = "JC_DirectBroadcast.Admin";
                    options.LoginPath = "/login.html";
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = TimeSpan.FromDays(1);
                });

            services.AddMemoryCache();
            services.AddOptions();
            //services.AddCors();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v2", new Info
                {
                    Version = "v2",
                    Title = "直播.Admin",
                    Description = "直播管理端 API",
                    TermsOfService = "None",
                    Contact = new Contact
                    {
                        Name = "jicai",
                        Email = string.Empty,
                        Url = "http://jc-edu.org"
                    },
                    License = new License
                    {
                        Name = "jicai"
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddSQLSugarClient<SqlSugarClient, DirectBroadcastDBContext>(config =>
            {
                config.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
                config.DbType = DbType.SqlServer;
                config.IsAutoCloseConnection = true;
                config.InitKeyType = InitKeyType.Attribute;
            });

            //services.AddScoped(typeof(IRepository<>), typeof(BaseRepository<>));

            return services.AddAutofacRegister(builder =>
            {
                //var dataAccess = Assembly.GetExecutingAssembly();

                //builder.RegisterAssemblyTypes(dataAccess)
                //    .Where(t => t.Name.StartsWith("tbl_"))
                //    .PublicOnly()
                //    .AsImplementedInterfaces();
                builder.RegisterType<tbl_SystemUser>();
                builder.RegisterGeneric(typeof(BaseRepository<>))
                    .As(typeof(IRepository<>))
                    .InstancePerLifetimeScope();
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "直播.Admin");
                c.DocumentTitle = "直播.Admin API";
            });

            app.UseMvcWithDefaultRoute();

            using (var scope = app.ApplicationServices.CreateScope())
            {
                //var db = scope.ServiceProvider.GetService<SqlSugarClient>();
                var re = scope.ServiceProvider.GetService<IRepository<tbl_SystemUser>>();
                re.Insert(new tbl_SystemUser()
                {
                    Id = Guid.NewGuid().ToString("N"),
                    UserName = "admin",
                    CreateTime = DateTime.Now,
                    CreateUser = "init",
                    DelTime = null,
                    DelUser = null,
                    EditTime = null,
                    EditUser = null,
                    IsDel = false,
                    Name = "超级管理员",
                    Password = "123456",
                    RoleId = "123456",
                    Sex = 1
                });
                //db.DbFirst.CreateClassFile(@"E:\TFS\JC_DirectBroadcast\SourceCode\JC_DirectBroadcast_v2\JC_DirectBroadcast\JC_DirectBroadcast.Core\Entity\", "JC_DirectBroadcast.Core.Entity");
            }

        }
    }
}
